package com.joint.web.action.manage;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.bean.DictBean;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Sets;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.UsersService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.manage.Qualifications;
import com.joint.core.entity.manage.QualificationsDict;
import com.joint.core.service.QualificationsDictService;
import com.joint.core.service.QualificationsService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/3/20.
 */
@ParentPackage("manage")
public class AjaxQualificationsAction extends BaseFlowAction {
    @Resource
    private QualificationsService qualificationsService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private QualificationsDictService qualificationsDictService;

    /**
     * 所属部门
     */
    private String departmentId;
    /**
     * 资质类别
     */
    private String type;
    /**
     * 资质类别读
     */
    private String typeText;
    /**
     * 资质名称
     */
    private String qualificationsDictId;
    /**
     *资质号
     */
    private String qualificationsNo;
    /**
     * 办理人员
     */
    private String handlerId;
    /**
     * 使用年限
     */
    private String useDate;
    /**
     * 评定日期
     */
    private String evaluateDate;
    /**
     * 提前提醒周期
     */
    private String remindDate;
    /**
     * 资质名称列表
     */
    private List<Map<String, Object>> qualificationsDictList;

    private Qualifications qualifications;
    private QualificationsDict qualificationsDict;
    private Users loginUser;
    private int numStatus;
    private String step;

    public String execute(){
        return "qualifications";
    }

    public String list(){
        pager = new Pager(0);
        /*
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);*/
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();

      //  params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        //  LogUtil.info("viewtype:" + viewtype);
        if(StringUtils.isNotEmpty(step)){
            if(step.equals("1")){
                //使用中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
                params.put("step", "1");
                params.put("invalid", false);
                pager=qualificationsService.findByPagerAndLimit(false, "qualifications", pager, params);
            }else if(step.equals("2")){
                //到期提醒
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
                params.put("step", "2");
                params.put("invalid", false);
                pager=qualificationsService.findByPagerAndFinish( "qualifications", pager, params);
            }else if(step.equals("3")){
                //已失效
                params.put("invalid", true);
                params.put("step", "3");
                pager=qualificationsService.findByPagerAndLimit(true, "qualifications", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=qualificationsService.findByPagerAndLimit(true, "qualifications", pager, params);
        }

        List<Qualifications> qualificationsList;
        if (pager.getTotalCount() > 0){
            qualificationsList = (List<Qualifications>) pager.getList();
        }else{
            qualificationsList= new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Qualifications q: qualificationsList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",q.getId());
            if(q.getType().equals("1")){
                rMap.put("type","企业证照");
            }else if(q.getType().equals("2")){
                rMap.put("type","企业资质");
            }else{
                rMap.put("type","未知");
            }
            rMap.put("qualificationsName",q.getQualificationsDict().getName());
            rMap.put("qualificationsNo",q.getQualificationsDict().getNo());
            rMap.put("evaluateDate",DataUtil.DateToString(q.getEvaluateDate(), "yyyy-MM-dd"));
            rMap.put("useDate",DataUtil.DateToString(q.getUseDate(), "yyyy-MM-dd"));
            rMap.put("state",q.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String input(){
        Company company = usersService.getCompanyByUser();
        Map<String,Object> rMap = null;
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("processState", new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Finished});
        List<QualificationsDict> list = (List<QualificationsDict>)qualificationsDictService.findByPagerAndCompany(null, null, company, params).getList();
        qualificationsDictList = new ArrayList<Map<String, Object>>();
        if(StringUtils.isNotEmpty(keyId)){
            qualifications=qualificationsService.get(keyId);
            for(QualificationsDict q:list){
                rMap = new HashMap<String, Object>();
                rMap.put("id",q.getId());
                rMap.put("name",q.getName());
                rMap.put("selected","");
                if(qualifications.getQualificationsDict()!=null && StringUtils.equals(q.getId(), qualifications.getQualificationsDict().getId())){
                    rMap.put("selected","selected");
                }
                qualificationsDictList.add(rMap);
            }
        }else{
            if(list.size()>0){
                for(QualificationsDict q:list){
                    rMap = new HashMap<String, Object>();
                    rMap.put("id",q.getId());
                    rMap.put("name",q.getName());
                    rMap.put("selected","");
                    qualificationsDictList.add(rMap);
                }
            }
        }
        return "input";
    }

    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)){
            typeText="";
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            qualifications=qualificationsService.get(keyId);
            if(qualifications.getType()!=null){
                if(qualifications.getType().equals("1")){
                    typeText="企业证照";
                }else if(qualifications.getType().equals("2")){
                    typeText="企业资质";
                }else{
                    typeText="未知";
                }
            }
        }

        return "read";
    }

    public String getInfo(){
        Map<String, Object> map = new HashMap<String, Object>();
        if(StringUtils.isNotEmpty(qualificationsDictId)){
            qualificationsDict=qualificationsDictService.get(qualificationsDictId);
            map.put("no",qualificationsDict.getNo());
        }
        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(map));
    }

    public int setData(){
        if(StringUtils.isNotEmpty(keyId)){
            qualifications=qualificationsService.get(keyId);
        }else{
            qualifications=new Qualifications();
            qualifications.setCreater(usersService.getLoginInfo());
        }
        qualifications.setDepartment(departmentService.get(departmentId));
        qualifications.setType(type);
        qualifications.setQualificationsDict(qualificationsDictService.get(qualificationsDictId));
        qualifications.setQualificationsNo(qualificationsNo);
        qualifications.setHandler(usersService.get(handlerId));
        qualifications.setUseDate(DataUtil.StringToDate(useDate));
        qualifications.setEvaluateDate(new Date());
        qualifications.setCompany(usersService.getLoginInfo().getCompany());
        long daysl=DataUtil.StringToDate(useDate).getTime()-new Date().getTime();
        int days=(int)(daysl/ (24 * 60 * 60 * 1000));
        System.out.println(DataUtil.StringToDate(useDate).getTime() + "-" + new Date().getTime() + "/" + 24 * 60 * 60 * 1000);
        if(days>=90){
            qualifications.setStep("1");
            System.out.println(days+"大于90天，设置1");
        }else if(days<90&&days>=0){
            qualifications.setStep("2");
            System.out.println(days+"小于90天，设置2");
        }else{
            qualifications.setStep("3");
            qualifications.setInvalid(true);
            System.out.println(days+"小于0天，设置3");
        }
        return days;
    }

    public String save(){
        int days=setData();
        if(days<0){
            return ajaxHtmlCallback("400", "使用年限不能小于当前时间！", "操作状态");
        }
        try {
            if(StringUtils.isNotEmpty(keyId)){
                qualificationsService.update(qualifications);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                qualificationsService.save(qualifications, "qualifications", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    // 提交
    public String commit(){
        int days=setData();
        if(days<0){
            return ajaxHtmlCallback("400", "使用年限不能小于当前时间！", "操作状态");
        }
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                qualificationsService.approve(qualifications, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
            } else {
                keyId = qualificationsService.commit(qualifications, FlowEnum.ProcessState.Finished,"qualifications", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //资质延续
    public String qContinue(){
        boolean isChange=false;
        if(StringUtils.isNotEmpty(keyId)){
            qualifications=qualificationsService.get(keyId);

            Set<Duty> dutySet=usersService.getLoginInfo().getDutySet();
            for(Duty duty:dutySet){
                Department dept=duty.getDepartment().getParent()==null?duty.getDepartment():duty.getDepartment().getParent();
                Department dept1=qualifications.getDepartment().getParent()==null?qualifications.getDepartment():qualifications.getDepartment().getParent();
                Post post=duty.getPost();
                if((StringUtils.equals(post.getName(),"行政负责人")||StringUtils.equals(post.getName(),"行政专员"))&&StringUtils.equals(dept.getId(),dept1.getId())){
                    isChange=true;
                    break;
                }
            }

            if(isChange){
                if(StringUtils.isNotEmpty(evaluateDate)){
                    qualifications.setEvaluateDate(DataUtil.StringToDate(evaluateDate));
                }else{
                    qualifications.setEvaluateDate(new Date());
                }
                qualifications.setUseDate(DataUtil.StringToDate(useDate));
                qualifications.setRemindDate(DataUtil.StringToDate(remindDate));

                if(DataUtil.StringToDate(useDate).getTime()<new Date().getTime()){
                    return ajaxHtmlCallback("400", "使用年限不能小于当前时间！", "操作状态");
                }
                if(DataUtil.StringToDate(useDate).getTime()>DataUtil.StringToDate(remindDate).getTime()){
                    return ajaxHtmlCallback("400", "使用年限不能大于提前提醒周期！", "操作状态");
                }
                if(new Date().getTime()>DataUtil.StringToDate(remindDate).getTime()){
                    qualifications.setStep("2");
                    qualifications.setInvalid(false);
                }else{
                    qualifications.setStep("1");
                    qualifications.setInvalid(false);
                }
                qualificationsService.update(qualifications);
            }else{
                return ajaxHtmlCallback("400", "没有权限！", "操作状态");
            }

        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }


    public String getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(String departmentId) {
        this.departmentId = departmentId;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getQualificationsNo() {
        return qualificationsNo;
    }

    public void setQualificationsNo(String qualificationsNo) {
        this.qualificationsNo = qualificationsNo;
    }

    public String getHandlerId() {
        return handlerId;
    }

    public void setHandlerId(String handlerId) {
        this.handlerId = handlerId;
    }

    public String getUseDate() {
        return useDate;
    }

    public void setUseDate(String useDate) {
        this.useDate = useDate;
    }

    public String getEvaluateDate() {
        return evaluateDate;
    }

    public void setEvaluateDate(String evaluateDate) {
        this.evaluateDate = evaluateDate;
    }

    public Qualifications getQualifications() {
        return qualifications;
    }

    public void setQualifications(Qualifications qualifications) {
        this.qualifications = qualifications;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }

    public String getStep() {
        return step;
    }

    public void setStep(String step) {
        this.step = step;
    }

    public String getTypeText() {
        return typeText;
    }

    public void setTypeText(String typeText) {
        this.typeText = typeText;
    }

    public String getRemindDate() {
        return remindDate;
    }

    public void setRemindDate(String remindDate) {
        this.remindDate = remindDate;
    }

    public String getQualificationsDictId() {
        return qualificationsDictId;
    }

    public void setQualificationsDictId(String qualificationsDictId) {
        this.qualificationsDictId = qualificationsDictId;
    }

    public List<Map<String, Object>> getQualificationsDictList() {
        return qualificationsDictList;
    }

    public void setQualificationsDictList(List<Map<String, Object>> qualificationsDictList) {
        this.qualificationsDictList = qualificationsDictList;
    }

    public QualificationsDict getQualificationsDict() {
        return qualificationsDict;
    }

    public void setQualificationsDict(QualificationsDict qualificationsDict) {
        this.qualificationsDict = qualificationsDict;
    }
}
